const CodeMain = require("../codemain");
const { getInfoFromServer } = require("./NetUtils");

function refreshLoginInfo(sucFunc, errFunc) {
    return new Promise((resolve, reject) => {
        let loginStr = localStorage.getItem("isLoginSuccess");
        loginInfo = loginStr && JSON.parse(loginStr);
        if (!loginInfo) {
            reject();
            errFunc instanceof Function && errFunc("请登录！");
            return;
        }
        sessionStorage.setItem("username", loginInfo.username);
        // 如果时间在一个小时之内，则使用原来的token
        let time = sessionStorage.getItem("getMasterTokenTime");
        if (time) {
            // 1000 * 60 * 60 = 3600000;
            let tokenExistTime = Date.now() - time;
            if (tokenExistTime < 3600000) {
                console.log(`%c使用保存的token: ${tokenExistTime}`, "color: #1200ff;");
                resolve(loginInfo);
                sucFunc instanceof Function && sucFunc(loginInfo);
                return;
            }
        }
        console.log(`重新请求token`, "color: #1200ff;");
        let username = loginInfo.username;
        let userId = loginInfo.userId;
        let infoObj = {
            url: `https://developers.masteropen.layabox.com/auth/reg_login?userId=${userId}&username=${username}`,
            openMethod: "GET",
            sendContent: null
        };
        getInfoFromServer(infoObj, (re) => {
            let reObj;
            try {
                reObj = re && JSON.parse(re);
            } catch(e) {
                reObj = null;
            }
            if (!reObj || 'object' !== typeof reObj || reObj.ret !== 0 || 'object' !== typeof reObj.data) {
                let errMsg = `getInfoObj=${JSON.stringify(getInfoObj)}\n re=${JSON.stringify(reObj)}`;
                throw new Error(errMsg);
            }
            let infoData = reObj.data;
            let token_master = infoData.token;
            let is_vip = infoData.is_vip;
            let is_enterprise = infoData.is_enterprise;
            let vip_end_at = infoData.vip_end_at;
            let devuid = infoData.uid;
            let isExec =  infoData.uuid; // 是否超过VIP绑定设备数量，因为仅在登录时提供，需要将该值传递

            // 更新登录信息
            loginInfo.token_master = token_master;
            loginInfo.is_vip = is_vip;
            loginInfo.is_enterprise = is_enterprise;
            loginInfo.vip_end_at = vip_end_at;
            loginInfo.devuid = devuid;
            loginInfo.isExec = isExec;
            if (typeof codeMain !== "undefined")
                codeMain.layaPageIns.setLoginInfo(loginInfo);
            resolve(loginInfo);
            sucFunc instanceof Function && sucFunc(loginInfo);
        });
    }).catch((err) => {
        errFunc instanceof Function && errFunc(err);
    })
}

function getLoginInfo() {
    let loginInfoObj;
    try {
        let loginStr;
        loginStr = localStorage.getItem("isLoginSuccess");
        loginInfoObj = loginStr && JSON.parse(loginStr);
    } catch (e) {
        loginInfoObj = null;
    }
    return loginInfoObj;
}

// sessionStorage.getItem("getMasterTokenTime"); // 获取token时间

module.exports = { refreshLoginInfo, getLoginInfo };